/**
 * Created by Toma on 2016/11/21.
 * 饼图
 */

var H5ComponentPie = function (name, cfg) {
  var compontent = new H5ComonentBase(name, cfg);

  // 绘制网格线
  var WIDTH = cfg.width;
  var HEIGHT = cfg.height;

  // 添加画布
  var cns = document.createElement('canvas');
  var ctx = cns.getContext('2d');
  cns.width = ctx.width = WIDTH;
  cns.height = ctx.height = HEIGHT;
  $(cns).css('z-index', 1);
  compontent.append(cns);

  // 绘制底层
  var r = WIDTH / 2;
  ctx.beginPath();
  ctx.fillStyle = '#eee';
  ctx.arc(r, r, r, 0, 2 * Math.PI, false);
  ctx.fill();


  /**
   * 绘制数据层
   * @param per 传入百分比
   */
  var cns = document.createElement('canvas');
  var ctx = cns.getContext('2d');
  cns.width = ctx.width = WIDTH;
  cns.height = ctx.height = HEIGHT;
  $(cns).css('z-index', 2);
  compontent.append(cns);

  var colors = ['red', 'green', 'blue', 'orange', '#445566', 'orange', 'yellow', '#333'];
  var sAngel = 1.5 * Math.PI;
  var eAngel = 0;
  var aAngel = Math.PI * 2;

  var step = cfg.data.length;
  for (var i = 0; i < step; i++) {
    var item = cfg.data[i];
    var color = item[2] || (item[2] = colors.pop());
    eAngel = sAngel + aAngel * item[1];

    ctx.beginPath();
    ctx.fillStyle = color;
    ctx.moveTo(r, r);
    ctx.arc(r, r, r, sAngel, eAngel, false);
    ctx.fill();
    sAngel = eAngel;

    // 注入文本
    var text = $('<div class="text">');
    text.text(cfg.data[i][0]);
    compontent.append(text);
    var per = $('<div class="per">');
    per.text(cfg.data[i][1] * 100 + '%')
    text.append(per);

    var x = r + Math.sin(Math.PI * .5 - sAngel) * r;
    var y = r + Math.cos(Math.PI * .5 - sAngel) * r;

    x > WIDTH / 2 ? text.css('left', x / 2) : text.css('right', (WIDTH - x) / 2);
    y > HEIGHT / 2 ? text.css('top', y / 2) : text.css('bottom', (HEIGHT - y) / 2 + 5);
    item[2] && text.css('color', item[2]);
  }
  H5ComponentPie.reSort(compontent.find('.text'));

  // 绘制蒙版层
  var cns = document.createElement('canvas');
  var ctx = cns.getContext('2d');
  cns.width = ctx.width = WIDTH;
  cns.height = ctx.height = HEIGHT;
  $(cns).css('z-index', 3);
  compontent.append(cns);

  var draw = function (per) {
    ctx.clearRect(0, 0, WIDTH, HEIGHT);
    ctx.beginPath();
    ctx.fillStyle = '#fff';
    ctx.moveTo(r, r);
    ctx.arc(r, r, r, sAngel, sAngel + 2 * Math.PI * per, true);
    ctx.fill();
  };

  // 折线生长动画
  compontent.on('onLoad', function () {
    var s = 0;
    for (i = 0; i < 100; i++) {
      setTimeout(function () {
        s += .01;
        draw(s);
      }, i * 10);
    }
  });
  compontent.on('onLeave', function () {
    var s = 1;
    for (i = 0; i < 100; i++) {
      setTimeout(function () {
        s -= .01;
        draw(s);
      }, i * 10);
    }
  });

  return compontent;
};

// 重排项目文本元素
H5ComponentPie.reSort = function (list) {
  // 1. 检测相交
  var compare = function (domA, domB) {
    
  };
  var reset = function () {
    
  };
}